class Util
{
    static prefixedEvent(element, type, callback) {
        let pfx = ["webkit", "moz", "MS", "o", ""];
        for (var p = 0; p < pfx.length; p++) {
            if (!pfx[p]) type = type.toLowerCase();
            Util.addEvent(element, pfx[p] + type, callback);
        }
    }

    static addEvent(ele, type, hander) {
        if (ele.addEventListener) {
            ele.addEventListener(type, hander, false);
        }
        if (ele.attachEvent) {
            ele.attachEvent('on' + type, hander);
        }
    }

    static screenHeight()
    {
        return document.body.clientHeight || document.documentElement.clientHeight  || window.screen.height || window.innerHeight  ;
    }

    static isX5()
    {
        let agent = navigator.userAgent
        return (/micromessenger/i).test(agent) || (/qqbrowser/i).test(agent);
    }

    static encodeHtml (s) {
        let REGX_HTML_ENCODE = /"|'|<|>|[\x00-\x20]|[\x7F-\xFF]|[\u0100-\u2700]/g
        return (typeof s != "string") ? null :
            s.replace(REGX_HTML_ENCODE,
                function($0){
                    var c = $0.charCodeAt(0), r = ["&#"];
                    c = (c == 0x20) ? 0xA0 : c;
                    r.push(c); r.push(";");
                    return r.join("");
                })
    }
}

class Event
{
    static on(eventName,func)
    {
        $(document).on(eventName, func);
    }

    static trigger(eventName,data)
    {
        $(document).trigger(eventName, data);
    }

    static off(eventName,func)
    {
        $(document).off(eventName, func);
    }

    static get EventConstant(){
        return EventConstant;
    };

};

class VideoPlayer
{
    constructor(props) {
        this.player;
        this.props = props;
        this.props.isLive = true;
        this._setup();
        this._bindEvent();
    }

    loadByUrl(url)
    {
        if(this.player)
            this.player.loadByUrl(url);
    }

    dispose()
    {
        if(this.player)
        {
            this.player.dispose();
            Zepto('#'+this.props.id).empty();
        }
    }

    _setup()
    {
        this.player = new Aliplayer(this.props,function(player){
            player._switchLevel = 0;
        });
    }

    _bindEvent()
    {
        var that = this;
        this.player.on('ready',  (e)=> {
            console.log('ready');
        });

        this.player.on('play',  (e)=>{
            console.log('play');

        });

        this.player.on('ended',(e)=>{
            console.log('ended');

        });
        this.player.on('pause',(e)=> {
            console.log('pause');

        });

        this.player.on('requestFullScreen', (e)=>{
            layout.adjustLayout(true);
            that.player.cancelFullScreen();
        });

        this.player.tag.addEventListener("x5videoexitfullscreen", ()=>{
            if(WeixinJSBridge)
                WeixinJSBridge.call('closeWindow');
        });

        // 解决ios不自动播放的问题
        $(document).on('WeixinJSBridgeReady',()=>{
            var video=$(that.player.el()).find('video')[0];
            video.play();
        });
    }

    _unbindEvent()
    {
        this.player.off('ready',function  (e) {
            console.log('ready');
        });

        this.player.off('play',function  (e) {
            console.log('play');

        });

        this.player.off('ended',function  (e) {
            console.log('ended');

        });
        this.player.off('pause',function  (e) {
            console.log('pause');

        });
    }

}

class CommentBuffer {
    constructor(wrapper, player) {
        this.comments = [];
        this.liveComment = new VideoComments(wrapper,player);
        let that = this;
        Event.on(Event.EventConstant.Comments_Sended, (e,data)=>{
            this.add(data);
        })
    }

    clear()
    {
        this.stop();
        this.liveComment.clear();
    }

    add(comment) {
        if (this.isStop)
            return;
        this.comments.push(comment);
        if (!this.isWorking) {
            this._wake();
        }
    }

    stop() {
        this.comments = [];
        this.isWorking = false;
        this.isStop = true;
        clearInterval(this.interval)
    }

    start() {
        this.isStop = false;
    }

    _wake() {
        this.isWorking = true;
        this.interval = setInterval(this._handle(), 100)
    }

    _handle() {
        var that = this;
        return function() {
            if (that.comments.length > 0) {
                if (that.liveComment.isFull()) {
                    that.liveComment.send("");
                }
                let comment = that.comments.shift();
                that.liveComment.send(comment);

            } else {
                that.isWorking = false;
                clearInterval(that.interval);
            }
        }
    }
}

const comment_row_template = '<div class="comment-row"><span class="comment-left"></span><span class="comment-right"></div>';
const comment_step= 25;
const container_max_rows= 20
const comment_name_colors= {
    '1': 'rgba(219,124,80,0.3)',
    '2': 'rgba(139,156,80,0.3)',
    '3': 'rgba(40,180,187,0.3)'
};
class VideoComments{
    constructor(wrapper) {
        this.createEl();
        this._setupComment();
        this.maxTopRow = null;
        this.colorIndex = 1;
    }

    createEl(wrapper) {
        this.comments = $('.comment-list');
        this.container = this.comments.find('.comment-container');
    }

    clear()
    {
        this.comments.empty();
    }

    isFull() {
        return this.comments.find('.empty-comment-row').length == 0;
    }

    send(comment) {
        let emptyRows = this.comments.children('.comment-row'),
            firstEmptyRow;

        if (!comment) {
            return;
        }

        if (emptyRows.length > 0)
            firstEmptyRow = $(emptyRows[0]);
        else
            firstEmptyRow = this._createEmptyRow();

        this._assignValues(firstEmptyRow, comment);

        this._move(firstEmptyRow);
    }

    _move(currentRow) {
        currentRow.show();
        let that = this,
            commentsHeight = this.comments.height(),
            containerHeight = this.container.height(),
            step = currentRow.height();
        this.container.append(currentRow);
        let row = this.container.children().first();
        if (containerHeight - commentsHeight > row.height()) {
            this._removeClass(row.find('.comment-right'));
            row.hide();
            this.comments.append(row);
        }
    }

    _assignValues(row, comment) {
        var name = row.find('.comment-left');
        name.text(comment.name);
        var commentRight = row.find('.comment-right');
        commentRight.html(comment.comment);
        commentRight.addClass(this._getClass());
    }

    _createEmptyRow() {
        let row = $(comment_row_template);
        row.hide()
        this.comments.append(row);
        return row;
    }

    _setupComment() {
        for (let i = 0; i < container_max_rows; i++) {
            this._createEmptyRow();
        }
    }


    _getClass(type) {
        if(this.colorIndex >4)
        {
            this.colorIndex = 1;
        }
        let className = 'comment-color'+this.colorIndex;
        this.colorIndex ++;
        return className;
    }

    _removeClass(ele) {
        ele.removeClass('comment-color1');
        ele.removeClass('comment-color2');
        ele.removeClass('comment-color3');
        ele.removeClass('comment-color4');
    }
}

class CommentSender
{
    static setup()
    {
        $('.comment-textbox .send-btn').click(()=>{
            let $text = $('.comment-textbox .send-txt');
            let msg = $text.val();
            if(msg == ''){
                msg = '不能发送空消息哦';
            }
            Event.trigger(Event.EventConstant.Comments_Sended, {
                name: UserInfo.name,
                comment: Util.encodeHtml(msg)
            });
            SendMessage(msg,UserInfo,'room_'+SellerId);
            $text.val("");
            WeixinJSBridge.call('hideToolbar');
            WeixinJSBridge.call('hideOptionMenu');
        });
        $('.comment-textbox .favoriate-send').click(()=>{
            Event.trigger(Event.EventConstant.Favoriation_Sended);
            getXin()
        });
    }
}

class Favoriate {
    constructor(images = ['/plugins/aliyun_live/Theme/mobile/images/xin.png', '/plugins/aliyun_live/Theme/mobile/images/xin.png', '/plugins/aliyun_live/Theme/mobile/images/xin.png', '/plugins/aliyun_live/Theme/mobile/images/xin.png', '/plugins/aliyun_live/Theme/mobile/images/xin.png', '/plugins/aliyun_live/Theme/mobile/images/xin.png']) {
        this.animateContainer = $('.favorite-animation-container');
        this.imgNames = images;
        this.index = 0;
        let that = this;
        Event.on(Event.EventConstant.Favoriation_Sended, ()=>{
            that.favoriate();
        })
    }

    favoriate() {
        let length = this.imgNames.length;
        this.index = (this.index < length) ? this.index : 0;
        name = this.imgNames[this.index];
        let $img = $(`<img src="${name}" class="favorite-animation" style="z-index: 999">`);
        this.animateContainer.append($img);
        this.index++;
        Util.prefixedEvent($img[0], 'animationend', () => {
            $img.remove();
        })
    }
}

class Header {

    constructor() {
        this.backup = [];
        this.max_count = 5;
    }


    setup(data) {
        let header = $('.video-header');
        header.find('.user-name').text(data.nickName);
        header.find('.user-head-img').attr('src', data.avatar);
        this._updateLikeNumber(data.likeNum);
        this._updateViewNumber(data.viewerNum);
        this._getAudiences();
        let that = this;
        Event.on(Event.EventConstant.Favoriation_Sended, ()=>{
            that._updateLikeNumber(1);
        });
        Event.on(Event.EventConstant.Viwer_Added, ()=>{
            that._updateViewNumber(1);
        })
    }

    _updateLikeNumber(number) {
        let ele = $('.video-header .user-favorite');
        let count = parseInt(ele.text());
        ele.text(count + number);
    }

    _updateViewNumber(number, userInfo) {
        if (number != null) {
            let ele = $('.video-header span.audience-count');
            let count = parseInt(ele.text());
            //ele.text(`${count+number} 人`);
            ele.text(`${number} 人`);
        }
        let wrapper = $('.audience-detail');
        Header.computeLeft($('.video-header .author'), wrapper);
        if (userInfo) {
            if (userInfo.type === 0) {
                if (!this.isFullHeaders) {
                    Header._createImgHeader(wrapper, userInfo.avatar, userInfo.uid);
                    this.isFullHeaders = (wrapper.find('.audience-header').length == this.max_count)
                } else {
                    $('.audience-detail .ellipsis').addClass('show');
                    this.backup.push(userInfo);
                }
            } else {
                if (this.backup.length > 0) {
                    let user = this.backup.pop(),
                        imgEle = wrapper.find('img[data-uid="' + userInfo.uid + '"]');
                    imgEle.attr('src', user.avatar);
                    imgEle.attr('data-uid', user.uid);

                } else {
                    wrapper.find('img[data-uid="' + userInfo.uid + '"]').remove();
                    $('.audience-detail .ellipsis').addClass('hide');
                    this.isFullHeaders = false;
                }
            }
        }
    }

    _updateViewHeadIco(userInfo) {
        let wrapper = $('.audience-detail');
        Header.computeLeft($('.video-header .author'), wrapper);
        if (userInfo) {
            if (userInfo.type === 0) {
                if (!this.isFullHeaders) {
                    Header._createImgHeader(wrapper, userInfo.avatar, userInfo.uid);
                    this.isFullHeaders = (wrapper.find('.audience-header').length == this.max_count)
                } else {
                    $('.audience-detail .ellipsis').addClass('show');
                    this.backup.push(userInfo);
                }
            } else {
                if (this.backup.length > 0) {
                    let user = this.backup.pop(),
                        imgEle = wrapper.find('img[data-uid="' + userInfo.uid + '"]');
                    imgEle.attr('src', user.avatar);
                    imgEle.attr('data-uid', user.uid);

                } else {
                    wrapper.find('img[data-uid="' + userInfo.uid + '"]').remove();
                    $('.audience-detail .ellipsis').addClass('hide');
                    this.isFullHeaders = false;
                }
            }
        }
    }

    _getAudiences(liveId, url) {
        for(let i=1;i<10;i++)
        {
            //Header._createImgHeader($('.audience-detail'), "./static/images/avatar.jpg", i);
        }
    }

    static _createImgHeader(wrapper, avatar, uid) {
        let img = $('<img  class="audience-header">');
        img.attr('src', avatar);
        img.attr('data-uid', uid);
        wrapper.prepend(img)

    }

    static computeLeft(audient, detail) {
        let w = audient.width() +  (20 / 68) * window.rem;
        detail.css('left', w);
    }
}

class Loading
{
    static show(backgroundOpacity=0)
    {
        if(backgroundOpacity!=0)
        {
            $('.loading-container').css('opacity',backgroundOpacity);
        }
        $('.loading-container').addClass('show');
    }
    static hide()
    {
        $('.loading-container').css('opacity',0);
        $('.loading-container').addClass('hide');
    }
}

const EventConstant ={
    Comments_Sended:'commentSended',
    Favoriation_Sended:'FavoriationSended',
    Viwer_Added:"viwerAdded"
};

class Layout
{
    static adjustLayout(excludeInputHeight = false)
    {
        let height = Util.screenHeight(),
            commentTextbox = $('.comment-textbox'),
            inputHeight = commentTextbox.height() +18;
        if(excludeInputHeight)
        {
            inputHeight = inputHeight*-1 +5;
        }
        commentTextbox.css('top', height - inputHeight);
        let commentList = $('.comment-list'),
            commentListHeight = commentList.height();
        commentList.css('top', height - commentListHeight - inputHeight);
        let favorioate = $('.favorite-animation-container'),
            favoritateHeight = favorioate.height();
        favorioate.css('top', height - favoritateHeight - inputHeight);
    }
}

function isWeiXinAndIos(){
    let ua = '' + window.navigator.userAgent.toLowerCase()
    let isWeixin = /MicroMessenger/i.test(ua)
    let isIos = /\(i[^;]+;( U;)? CPU.+Mac OS X/i.test(ua)
    return isWeixin && isIos
}

function  weChatInputBug() {
    let myFunction;
    let isWXAndIos = isWeiXinAndIos();
    if (isWXAndIos) {
        document.body.addEventListener('focusin', () => {
            clearTimeout(myFunction);
            WeixinJSBridge.call('hideToolbar');
            WeixinJSBridge.call('hideOptionMenu');
        });
        document.body.addEventListener('focusout', () => {
            clearTimeout(myFunction);
            myFunction = setTimeout(function () {
                window.scroll1To({top: 0, left: 0, behavior: 'smooth'})
            }, 200);
            WeixinJSBridge.call('hideToolbar');
            WeixinJSBridge.call('hideOptionMenu');
        });
    }
}

var comment,commentBuffer, favoriate, header;

$(()=>{
    var player = new Aliplayer({
        id: 'J_prismPlayer',
        autoplay: true,
        isLive:true,
        height:"100%",
        width:"100%",
        playsinline:true,
        source: playUrl,
        // source:"https://player.alicdn.com/resource/player/big_buck_bunny.mp4",
        useH5Prism:true,
        useFlashPrism:false,
        //cover:onlineRow.room_desc,
        //prismplayer 2.0.1版本支持的属性，主要用户实现在android 微信上的同层播放
        x5_type:'h5', //通过 video 属性 “x5-video-player-type” 声明启用同层H5播放器，支持的值：h5 https://x5.tencent.com/tbs/guide/video.html
        x5_fullscreen:true,//通过 video 属性 “x5-video-player-fullscreen” 声明视频播放时是否进入到 TBS 的全屏模式，支持的值：true
        skinLayout:[
            {name:"bigPlayButton", align:"blabs", x:"70", y:"150"},
            {name: "H5Loading", align: "cc"},
            {name: "errorDisplay", align: "tlabs", x: 0, y: 0},
            {name: "infoDisplay", align: "cc"}
        ]
    }, function (player) {
        console.log("The player is created");
    });
    //在播放出错时
    player.on('onM3u8Retry',function(){
        console.log('主播暂时离开，请稍后......');
    });

    //当尝试数据恢复失败时
    player.on('liveStreamStop',function(e)
    {
        var errHtml = '<div style="width:100%; height:100%;line-height: 10rem;position: relative;font-size:.5rem;color: rgba(0,0,0,.8);;background-size:cover;background-image:url(/plugins/aliyun_live/public/images/bg.jpg)"><center>直播失败或直播已结束!</center></div>';
        $('#J_prismPlayer').html(errHtml);
       // player.loadByUrl('/plugins/aliyun_live/public/images/bg.jpg'); //切换另外一路可用流
        console.log('直播失败或直播已结束');
    });



    // 解决ios不自动播放的问题
    wx.config({
        // 配置信息, 即使不正确也能使用 wx.ready
        debug: false,
        appId: '',
        timestamp: 1,
        nonceStr: '',
        signature: '',
        jsApiList: []
    });
    wx.ready(function() {
        var video=$(player.el()).find('video')[0];
        video.play();
    });

    CommentSender.setup();
    comment = new Comment();
    commentBuffer = new CommentBuffer();
    favoriate  = new Favoriate();
    header = new Header();
    header.setup({
        nickName:onlineRow.room_name,
        avatar:'/'+sellerInfo.logo,
        likeNum:0,
        viewerNum:0
    });
    Layout.adjustLayout();
    Loading.hide();

    document.onkeydown = function (e) { // 回车提交表单
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
        if (code == 13) {
            console.log(code)
            $(".send-btn").trigger('click');
        }
    };
});